import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Toast, Dialog, Input, Popup, TextArea } from 'antd-mobile'
import { CloseOutline } from 'antd-mobile-icons'
import HeadTop from '@/components/HeadTop';
import CheckItems from '@/components/CheckItems';
import FootButton from '@/components/FootButton';
import UploadPhotos from '@/components/UploadPhotos';
import Loading from '@/components/Loading';

import PickerSelectMore from '@/components/PickerSelectMore';
import Index from '@/api/maintenance';
import { add_check_cache, decrement_check_cache } from '@/Store/action';
import { connect } from 'react-redux';
import "./index.less"

function Detail(props) {
    const [detaiObj, setDetaiObj] = useState({ itemVoList: [] });
    const [sureButtonTxt, setSureButtonTxt] = useState("开始保养")
    const [reason, setReason] = useState('')
    const uploadRef = useRef()
    const detailRef = useRef(detaiObj)
    const navigate = useNavigate();
    const [loading, setLoading] = useState(false);

    const [visible, setVisible] = useState(false)
    const [partsListNo, setPartsListNo] = useState('')

    const [value, setValue] = useState(1)

    useEffect(() => {
        getInfoDetail()
    }, []);

    useEffect(() => {
        const unlisten = navigate((path, action) => {
            if (action === 'POP') {
                changeCache('add_check_cache');
            }
        });
        return unlisten;
    }, [navigate]);

    const changeCache = (type) => {
        let oc = {
            no: detailRef.current.no,
            items: detailRef.current.itemVoList
        }
        props[type](oc)
    }

    const getFilterCache = (data) => {
        let o = data
        if (props.checkItemsCache.length) {
            let c = props.checkItemsCache.findIndex(el => el.no == data.no)
            if (c > -1) {
                o = {
                    ...data,
                    itemVoList: props.checkItemsCache[c].items
                }
            }
        }

        return o
    }

    const getInfoDetail = () => {
        setLoading(true)
        Index.loadByNo(props.location.state.no).then(res => {
            setLoading(false)
            const result = res.data
            if (result.code) {
                Toast.show({
                    content: '请求失败:' + result.msg,
                })
                return
            }
            // 获取缓存check cache
            let rdata = JSON.parse(JSON.stringify(result.data));
            if (rdata.itemVoList?.length) {
                if (result.data.status == 'PROCESSING') {
                    rdata.itemVoList.forEach(el => el.inspectionResult = '')
                }
            }
            let _data = getFilterCache(rdata)
            setDetaiObj(_data)
            detailRef.current = _data

            // setDetaiObj(result.data)
            uploadRef.current && uploadRef.current.setPhotoListFinish(result.data?.photoUrl || [])
            if (result.data.status == 'PROCESSING') {
                setSureButtonTxt("完成保养")
            }
        })
    }

    const getSubmitSure = () => {
        let txt = detaiObj.status == 'WAIT_FINISH' ? '确定开始保养' : '确定完成保养'
        if (txt == '确定完成保养') {
            let noCheck = []
            detaiObj.itemVoList.forEach((el, index) => {
                if (!el.inspectionResult) {
                    noCheck.push(index + 1)
                }
            })
            if (noCheck.length) {
                Toast.show({
                    content: `第${noCheck.join(" ")}项未选择`,
                })
                return
            }
            console.log(value,'val')
            if(!value  || value < 1 ){
                Toast.show({
                    content: '请输入维修人员数量',
                })
                return
            }
        }
        Dialog.confirm({
            content: txt,
            onConfirm: async () => {
                handleSubmit()
            },
        })
    }

    const handleSubmit = () => {

        // if (detaiObj.status == 'PROCESSING') {
        //     let noR = false
        //     detaiObj.itemVoList.some(el => {
        //         if (!el.inspectionResult) {
        //             noR = true
        //         }
        //     })
        //     if (noR) {
        //         Toast.show({
        //             content: '请选择检验结果!',
        //         })
        //         return
        //     }
        // }


        setLoading(true)
        let params = {
            no: detaiObj.no,
            status: detaiObj.status,
            itemList: detaiObj.itemVoList,
            remark: reason,
            photoUrl: uploadRef.current ? uploadRef.current.photoList.join(",") : '',
            sparePartsNo: partsListNo.length && partsListNo.map(el => el.no).join(','),
            number: value
        }
        let api = Index.startMaintain
        if (detaiObj.status == 'PROCESSING') {
            api = Index.finishMaintain
        }
        api(params).then(res => {
            setLoading(false)
            if (res.data.code) {
                Toast.show({
                    content: '请求失败:' + res.data.msg,
                })
                return
            }
            Toast.show({
                content: '提交成功',
            })
            changeCache('decrement_check_cache')
            getInfoDetail()
        })
    }

    const submitModal = (items) => {
        setVisible(false)
        setPartsListNo(prev => {
            return [
                ...prev,
                ...items
            ]
        })
    }

    const closePartsLists = (e) => {
        e.stopPropagation()
        setPartsListNo([])
    }
    return (
        <div className='page-wrapper'>
            {
                loading ? <Loading></Loading> : null
            }
            <HeadTop title="设备保养详情" history={props.history}></HeadTop>
            <div className="page-body">
                <div className="info">
                    <div className="d-title">保养单编号:{detaiObj.no}</div>
                    <div className="info-main">
                        <div className="m-line">
                            <div className="m-name">保养状态</div>
                            <div className="m-val">{detaiObj.status == 'WAIT_FINISH' ? '待保养' : (
                                detaiObj.status == 'PROCESSING' ? '进行中' : '已完成'
                            )}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">设备编号：</div>
                            <div className="m-val">{detaiObj.deviceCode}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">设备名称：</div>
                            <div className="m-val">{detaiObj.deviceName}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">任务名称：</div>
                            <div className="m-val">{detaiObj.strategyNames}</div>
                        </div>
                        <div className="m-line">
                            <div className="m-name">计划时间：</div>
                            <div className="m-val">{detaiObj.planInspectionTime}</div>
                        </div>
                    </div>
                </div>
                <div className="result">
                    <div className="d-title">设备保养项目</div>
                    {
                        detaiObj.itemVoList?.length ?
                            (detaiObj.itemVoList.map(el =>
                                <CheckItems
                                    key={el.no}
                                    info={el}
                                    detaiObj={detaiObj}
                                ></CheckItems>
                            )) :
                            <div className='no-detail-data'>暂无更多数据</div>
                    }
                </div>
                {
                    detaiObj.status !== 'WAIT_FINISH' ? <div className="device">
                        <div className="d-title">备件备品领用</div>
                        <div className="show-device-list" onClick={() => detaiObj.status !== 'FINISH' && setVisible(true)}>

                            {
                                partsListNo.length ?
                                    partsListNo.map(el =>
                                        <span key={el.id}>{el.no},</span>
                                    ) : <span>请选择备件备品领用</span>

                            }
                            {
                                partsListNo.length ? <div className='closeIcon' onClick={e => closePartsLists(e)}>
                                    <CloseOutline />
                                </div> : null
                            }

                        </div>
                    </div> : null
                }
                {
                    detaiObj.status !== 'WAIT_FINISH' ? <div className="reason">
                        <div className="d-title">设备保养原因</div>
                        <TextArea
                            placeholder='请输入保养原因'
                            clearable
                            className='bc'
                            disabled={detaiObj.status == 'FINISH'}
                            value={reason}
                            onChange={val => { setReason(val) }}
                            type='textarea'
                        />
                    </div> : null
                }
                {
                    detaiObj.status !== 'WAIT_FINISH' ?
                        <div className="photos">
                            <div className="d-title">设备保养图</div>
                            <UploadPhotos
                                ref={uploadRef}
                                detaiObj={detaiObj}
                                showUpload="PROCESSING"
                            />
                        </div> : null
                }
                {
                    detaiObj.status !== 'WAIT_FINISH' ?
                        <div className="photos">
                            <div className="d-title">维修人员数量</div>
                            <Input
                                className='bc'
                                placeholder='请输入维修人员数量'
                                value={value}
                                disabled={detaiObj.status == 'FINISH'}
                                onChange={val => {
                                    setValue(val)
                                }}
                            />
                        </div> : null
                }
            </div>
            {
                (detaiObj.status == 'WAIT_FINISH' || detaiObj.status == 'PROCESSING') ?
                    <FootButton
                        cancelTxt="返回"
                        sureTxt={sureButtonTxt}
                        getSubmitCancel={() => navigate(-1)}
                        getSubmitSure={getSubmitSure}>
                    </FootButton> :
                    null
            }
            {/* 备件 列表 */}
            <Popup
                className='select-more-picker'
                visible={visible}
                onMaskClick={() => {
                    setVisible(false)
                }}
                bodyStyle={{ height: '60vh' }}
            >
                <PickerSelectMore
                    close={() => setVisible(false)}
                    submit={submitModal}></PickerSelectMore>
            </Popup>

        </div>
    );
}

const mapStateToProps = (state) => {
    return {
        checkItemsCache: state.checkItemsCache,
    };
};

const mapDispatchToProps = {
    add_check_cache,
    decrement_check_cache
};


export default connect(mapStateToProps, mapDispatchToProps)(Detail);
